#include <stdio.h>
#include <pthread.h>
// 这是mt.c的mutex版本，比较耗时，但是通用性和正确性会好一些
int a;

pthread_mutex_t mutex;

void* sum(void* args)
{
	for (volatile int i = 0; i < 10000000; i++)
	{
		pthread_mutex_lock(&mutex);
		a++;
		pthread_mutex_unlock(&mutex);
	}
	return NULL;
}

void test(void)
{
	a = 0;
	pthread_t t1, t2;
	pthread_create(&t1, NULL, sum, NULL);
	pthread_create(&t2, NULL, sum, NULL);

	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	printf("a = %d\n", a);
}

int main(void)
{
	pthread_mutex_init(&mutex, NULL);
	test();
	// test();
	// test();
	return 0;
}
